package cn.sjxy.baseLib;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.util.HashMap;

/**
 * 构造AJAX请求的返回结果
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AjaxResult extends HashMap<String, Object> {
    /*状态码标识*/
    public static final String CODE_TAG = "code";

    /*返回消息标识*/
    public static final String MSG_TAG = "msg";

    /*初始化一个新创建的 AjaxResult 对象*/
    public AjaxResult(int code, String msg) {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
    }

    /*添加键值数据*/
    public AjaxResult addKey(String key, Object value) {
        super.put(key, value);
        return this;
    }

    /*添加表格数据*/
    public AjaxResult addTable(Object listData) {
        put("table", listData);
        return this;
    }

    /*添加分页参数*/
    public AjaxResult addPage(IPage page) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(page.getCurrent());
        pageInfo.setPageSize(page.getSize());
        pageInfo.setRowCount(page.getTotal());
        pageInfo.setPageCount(page.getPages());
        super.put("pager",pageInfo);
        return this;
    }

    /*请求成功*/
    public static AjaxResult success(String msg) {
        AjaxResult result = new AjaxResult(200, msg);
        return result;
    }

    /*请求出错 - 系统内部错误*/
    public static AjaxResult error(String msg) {
        AjaxResult result = new AjaxResult(500, msg);
        return result;
    }

    /**
     * 设置错误类型,code代表不同的错误类型
     *
     * @param code 401 登录问题
     * @return
     */
    public void setCode(int code) {
        super.put(CODE_TAG, code);
    }

}
